import React, { useRef, useEffect } from 'react';
import { Button } from 'antd';

import BpmnViewer from 'bpmn-js/lib/NavigatedViewer';
import EmbeddedComments from 'bpmn-js-embedded-comments';

import 'bpmn-js/dist/assets/diagram-js.css';

import { withMenu } from '~/components/Menu';
import { XmlView2 } from '~/utils/const';
import { initEventBus, initOverlays } from '~/utils/listeners';

const View = (props) => {
  const viewer = useRef();

  const init = () => {
    viewer.current = new BpmnViewer({
      container: '#canvas',
      additionalModules: [EmbeddedComments],
    });
  };

  const downloadXml = () => {
    viewer.current.saveXML({ format: true }).then((e) => {
      console.log('saveXML', e);
    });
  };

  const loadXml = () => {
    const Bpmn = viewer.current;

    Bpmn.importXML(XmlView2)
      .then(() => {
        initEventBus(viewer.current);
        initOverlays(viewer.current);
      })
      .catch((err) => {
        console.error('failed to load diagram', err);
      });
  };

  useEffect(() => {
    init();
    loadXml();
  }, []);

  return (
    <div className="page-bpmn-view">
      <div className="page-left" id="canvas"></div>
      <div className="page-right">
        <div className="page-foot">
          <Button block onClick={() => downloadXml()}>
            下载
          </Button>
        </div>
      </div>
    </div>
  );
};

export default withMenu(View);
